package com.mm.controller.web.user;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.AopLog;
import com.mm.base.annotation.VerifyToken;
import com.mm.util.result.DPage;
import com.mm.util.result.DResult;
import com.mm.domain.user.DUser;
import com.mm.serivce.user.IDUserService;
import com.mm.vo.web.user.AuthMenuVo;
import com.mm.vo.web.user.DownTreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author JueDream
 * @since 2021-08-04
 */
@Api(value = "/u/v1", tags = {"用户信息"})
@Slf4j
@VerifyToken
@RestController
@RequestMapping("/u/v1")
@AopLog(type = "用户信息", stackTraceOnErr = true)
public class DUserController {

    private final IDUserService userService;

    public DUserController(IDUserService userService) {
        this.userService = userService;
    }


    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", dataTypeClass = Integer.class, name = "page", value = ""),
            @ApiImplicitParam(paramType = "query", dataType = "int", dataTypeClass = Integer.class, name = "limit", value = ""),
            @ApiImplicitParam(paramType = "query", dataType = "string", dataTypeClass = String.class, name = "queryByLoginName", value = "")
    })
    @ApiOperation(value = "用户信息列表查询接口", notes = "", httpMethod = "POST")
    @PostMapping("/queryUserPage")
    public DResult queryUserPage(@RequestParam int page, @RequestParam int limit, @RequestParam(required = false) String queryByLoginName){
        Page<DUser> userInfoPage = userService.queryUserPage(page, limit, queryByLoginName);
        DPage<DUser> userPage = DPage.to(userInfoPage);
        return DResult.of(userPage);
    }

    @ApiOperation(value = "司机信息列表查询接口", notes = "", httpMethod = "GET")
    @GetMapping("/queryUserDriver")
    public DResult queryUserDriver(){
        List<DUser> userList = userService.queryUserAll();
        List<DownTreeVo> downTreeVos = new ArrayList<>();
        Optional.ofNullable(userList).orElse(new ArrayList<>())
                .forEach(u -> {
                    downTreeVos.add(DownTreeVo.builder().id(u.userId)
                    .title(u.userName).build());
                });
        return DResult.of(downTreeVos);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", dataTypeClass = Integer.class, name = "userId", value = "")
    })
    @ApiOperation(value = "用户信息查询单个接口", notes = "", httpMethod = "POST")
    @PostMapping("/queryUserOne")
    public DResult queryUserOne(@RequestParam Integer userId){
        return DResult.of(userService.findUserById(userId));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "DUser", dataTypeClass = DUser.class, name = "user", value = "")
    })
    @ApiOperation(value = "用户信息编辑接口", notes = "", httpMethod = "POST")
    @Transactional
    @PostMapping("/saveOrUpdate")
    public DResult saveOrUpdate(@RequestBody DUser user) {
        boolean flag = false;
        if (user.getUserId() < 0) {
            // 新增
            flag = userService.save(user);
        } else if (user.getUserId()  > 0) {
            // 更新
            flag = userService.updateById(user);
        }
        return DResult.of(flag);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", dataTypeClass = Integer.class, name = "userId", value = "")
    })
    @ApiOperation(value = "用户信息删除接口", notes = "", httpMethod = "DELETE")
    @DeleteMapping("/delete")
    public DResult delete(@RequestParam Integer userId){
        boolean flag = false;
        if (userId > 0) {
            flag = userService.removeUser(userId);
        }
        return DResult.of(flag);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Map<String, Object>", dataTypeClass = Map.class, name = "map", value = "")
    })
    @ApiOperation(value = "绑定用户角色菜单接口", notes = "", httpMethod = "POST")
    @PostMapping("/bindAuth")
    public DResult bindAuth(@RequestBody Map<String, Object> map){
        Integer userId = Integer.parseInt(map.get("userId").toString());
        List<Integer> roleIds = new ArrayList<>();
        String roleIdStr = map.get("roleIds").toString();
        if (StrUtil.isNotBlank(roleIdStr)){
            roleIds = Arrays.asList(roleIdStr.split(",")).stream()
                    .map(s -> Integer.valueOf(s.trim()))
                    .collect(Collectors.toList());
        }
        List<Integer> pIds = new ArrayList<>();
        String pIdStr = map.get("pIds").toString();
        if (StrUtil.isNotBlank(pIdStr)){
            pIds = Arrays.asList(pIdStr.split(",")).stream()
                    .map(s -> Integer.valueOf(s.trim()))
                    .collect(Collectors.toList());
        }
        AuthMenuVo vo = AuthMenuVo.builder().userId(userId).roleIds(roleIds).pIds(pIds).build();
        // 判断用户是否存在
        if (vo.getUserId() > 0) {
            DUser user =  userService.findUserById(vo.getUserId());
            if (Objects.isNull(user)){
                return DResult.failed("用户不存在");
            }
            if (userService.bindAuthMenu(vo)) {
                return DResult.success();
            }
        }
        return DResult.failed();
    }
}
